﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Windows.Data;
using DataLayer.Types;

namespace ViewModel.Aggregators
{
    public class TotalsSumConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string defaultValue = 0.ToString("C");
            if (values == null) return defaultValue;

            try
            {
                ObservableCollection<BudgetItem> budgetItems = values[0] as ObservableCollection<BudgetItem>; 
                if(budgetItems == null)
                {
                    string foundType = values[0] == null ? "null" : values[0].GetType().Name;
                    log4net.LogManager.GetLogger(GetType()).Error("Wrong type. Expected 'ObservableCollection<BudgetItem>', found '" + foundType + "'");
                    return defaultValue;
                }

                FrequencyItem frequencyItem = values[1] as FrequencyItem;
                if(frequencyItem == null)
                {
                    string foundType = values[1] == null ? "null" : values[1].GetType().Name;
                    log4net.LogManager.GetLogger(GetType()).Error("Wrong type. Expected 'FrequencyItem', found '" + foundType + "'");
                    return defaultValue;
                }

                BalanceType balanceType = values[2] as BalanceType;
                if(balanceType == null)
                {
                    string foundType = values[2] == null ? "null" : values[2].GetType().Name;
                    log4net.LogManager.GetLogger(GetType()).Error("Wrong type. Expected 'BalanceType', found '" + foundType + "'");
                    return defaultValue;
                }

                return AggregateTools.CalculateTotalPeriodicPayment(budgetItems, frequencyItem, balanceType).ToString("C");
            }
            catch(InvalidCastException ice)
            {
                        
                log4net.LogManager.GetLogger(GetType()).Error("Could not convert properties to a decimals", ice);
                return null;
            }
        }


        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }


    }
}
